import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Cascader, Popconfirm, message } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import { getCityManagerList, setCityManagerStatus } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import CityModal from './components/CityModal';
import OrgSelect from '@/components/OrgSelect';
import { queryCityOptions2 } from '@/services/common';
import { jump2target } from '@/utils/common';

const EquipmentPage: React.FC<RoutePageProps> = (props) => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<any>()
  const [searchParams, setSearchParams] = useState<any>({
    pageNum: 1, pageSize: 10,
  })
  const stubList = useRequest(() => getCityManagerList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [cityModalProps, setCityModalProps] = useState<any>({
    open: false
  })
  const cityOptions = useRequest(queryCityOptions2)
  const setStatusReq = useRequest(setCityManagerStatus, {manual: true})

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      orgId: formValues.org?.id,
      city: formValues.city?.at(-1),
      pageNum: 1,
    })
  }
  
  const onCityModalCancel = () => {
    stubList.refresh()
    setCityModalProps({open: false})
  }

  const openEditModal = (record?: any) => {
    setCityModalProps({
      open: true,
      infoId: record.infoId
    })
  }

  const setStatus = (record: any, status: number) => {
    return setStatusReq.runAsync({
      infoId: record.infoId,
      status: status,
    }).then(() => {
      const statusTextMap = ['', '启用', '禁用', '删除']
      message.success(`${statusTextMap[status]}成功`)
      stubList.refresh()
    })
  }

  const jump2orgDetail = (id: number) => {
    jump2target(`/station/org/detail?type=edit&id=${id}`, {needRefresh: true})
    sessionStorage.setItem('__/station/org/detail_title', '经销商详情')
  }

  const jump2editPage = (record?: any) => {
    jump2target('/station/cityMList/edit', {
      name: record ? '编辑城市经理人' : '添加城市经理人',
      params: record,
      needRefresh: true,
    })
  }

  const columns: ColumnsType = [
    {
      title: '经销商',
      dataIndex: 'orgName',
      width: 120,
      render: (val, record) => {
        return <a onClick={() => jump2orgDetail(record.id)}>{val}</a>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'fromTime',
      width: 120,
    },
    {
      title: '城市权限',
      dataIndex: 'cityNames',
      width: 120,
    },
    {
      title: '第一年抽成比例',
      dataIndex: 'oneYear',
      width: 120,
    },
    {
      title: '第二年抽成比例',
      dataIndex: 'twoYear',
      width: 120,
    },
    {
      title: '第三年抽成比例',
      dataIndex: 'thirdYear',
      width: 120,
    },
    {
      title: '第四年抽成比例',
      dataIndex: 'fourYear',
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 240,
      render: (id: number, record) => {
        return <Space>
          <Access accessible={record.cityStatus === 1}>
            <Popconfirm title='确认禁用吗?' onConfirm={() => setStatus(record, 2)}>
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.cityStatus === 2}>
            <Popconfirm title='确认启用吗?' onConfirm={() => setStatus(record, 1)}>
              <a>启用</a>
            </Popconfirm>
          </Access>
          <a onClick={() => openEditModal(record)}>城市权限</a>
          <a onClick={() => jump2editPage(record)}>编辑</a>
          <Access accessible={record.cityStatus === 2}>
            <Popconfirm title='确认删除吗?' onConfirm={() => setStatus(record, 3)}>
              <a>删除</a>
            </Popconfirm>
          </Access>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      stubList.refresh()
    }
    window.addEventListener('refreshCityManagerList', refresh)
    return () => {
      window.removeEventListener('refreshCityManagerList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => jump2editPage()}>添加城市经理人</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchCityForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='经销商' name='org'>
                  <OrgSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name='city' label='城市'>
                  <Cascader
                    changeOnSelect
                    loading={cityOptions.loading}
                    options={cityOptions.data?.data}
                    style={{width: 320}}
                    placeholder='请选择'
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={stubList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table
          rowKey='id'
          loading={stubList.loading}
          dataSource={stubList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: stubList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <CityModal
        {...cityModalProps}
        onCancel={onCityModalCancel}
      />
    </div>
  );
};

export default EquipmentPage;
